<template>
  <transition name="el-zoom-in-center">
    <div class="cu-preview-main campus-form">
      <div class="cu-common-page-header">
        <el-page-header @back="goBack" :content="!dataForm.id ? '新建' : isDetail ? '详情' : '编辑'" />
        <div class="btns">
          <el-button type="primary" @click="dataFormSubmit()" v-if="!isDetail">确 定</el-button>
          <el-button @click="goBack">取 消</el-button>
        </div>
      </div>
      <div class="main" v-loading="loading">
        <el-form ref="elForm" :model="dataForm" size="small" label-width="120px" label-position="right" :disabled="!!isDetail" :rules="rules">
          <!-- 基本信息区：包含标题、模式、类型、证书与宣传图等核心信息，用于定义师训的基础属性 -->
          <el-card class="cu-section-card" shadow="never">
            <div slot="header">
              <groupTitle content-identity="left" content="基本信息" icon="el-icon-document"></groupTitle>
            </div>
            <el-row :gutter="16">
              <el-col :xs="24" :sm="12" :md="12" :lg="12" v-if="custom.hasFormP('title')">
                <el-form-item label="师训标题" prop="title">
                  <el-input v-model="dataForm.title" placeholder="示范：第xx期安亲老师岗位培训（线上/地区）" clearable required :style="{ width: '100%' }"></el-input>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="12">
                <el-form-item label="师训模式" prop="title">
                  <el-select v-model="dataForm.model" placeholder="请选择师训模式" filterable clearable required :style="{ width: '100%' }">
                    <el-option :key="item.enCode" :label="item.fullName" :value="item.enCode" v-for="item in modelOptions" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="16">
              <el-col :xs="24" :sm="24" :md="24" :lg="24">
                <div ref="mapPreview" class="map-preview"></div>
              </el-col>
            </el-row>
            <el-row :gutter="16">
              <el-col :xs="24" :sm="12" :md="12" :lg="12" v-if="custom.hasFormP('typeId')">
                <el-form-item label="师训类型" prop="typeId">
                  <el-select v-model="dataForm.typeId" placeholder="请选择" clearable required :style="{ width: '100%' }">
                    <el-option v-for="(item, index) in typeIdOptions" :key="index" :label="item.fullName" :value="item.enCode"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="12" v-if="custom.hasFormP('certificateTemplate')">
                <el-form-item label="证书模版" prop="certificateTemplate">
                  <el-select v-model="dataForm.certificateTemplate" placeholder="请选择" clearable required :style="{ width: '100%' }" filterable lastLevel>
                    <el-option-group v-for="group in certificateTemplateOptions" :key="group.id" :label="group.fullName">
                      <el-option v-for="item in group.children" :key="item.id" :label="item.fullName" :value="item.enCode"></el-option>
                    </el-option-group>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="16">
              <el-col :xs="24" :sm="24" :md="24" :lg="24" v-if="custom.hasFormP('picture')">
                <el-form-item label="宣传图片" prop="picture">
                  <custom-upload-img v-model="dataForm.picture" :fileSize="5" sizeUnit="MB" type="train" :limit="1" required></custom-upload-img>
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>
          <el-divider></el-divider>

          <!-- 权限控制区：用于控制品牌与推送区域，可影响校区可见范围与报名入口展示 -->
          <el-card class="cu-section-card" shadow="never">
            <div slot="header">
              <groupTitle content-identity="left" content="权限控制" icon="el-icon-lock"></groupTitle>
            </div>
            <el-row :gutter="16">
              <el-col :xs="24" :sm="12" :md="12" :lg="12" v-if="custom.hasFormP('brand')">
                <el-form-item label="校区品牌" prop="brand">
                  <el-select v-model="dataForm.brand" placeholder="请选择校区品牌" filterable clearable required :style="{ width: '100%' }" multiple>
                    <el-option :key="item.id" :label="item.fullName" :value="item.enCode" v-for="item in brandOptions" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="12" v-if="custom.hasFormP('pushCampus')">
                <el-form-item label="推送区域" prop="pushCampus" :style="{ width: '100%' }">
                  <custom-address v-model="dataForm.pushCampus" :multiple="true" checkStrictly clearable :styleWidth="{ width: '100%' }"></custom-address>
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>
          <!-- 报名设置区：包含费用、日期与超额策略等与报名相关的配置 -->
          <el-card class="cu-section-card" shadow="never">
            <div slot="header">
              <groupTitle content-identity="left" content="报名设置" icon="el-icon-tickets"></groupTitle>
            </div>
            <el-row :gutter="16">
              <el-col :xs="24" :sm="12" :md="6" :lg="6" v-if="custom.hasFormP('free')">
                <el-form-item label="是否免费" prop="free">
                  <el-switch v-model="dataForm.free" :active-value="1" :inactive-value="0" :style="{ width: '100%' }"></el-switch>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="6" :lg="6" v-if="custom.hasFormP('price')">
                <el-form-item label="收费价格" prop="price">
                  <el-input v-model="dataForm.price" placeholder="请输入" clearable required></el-input>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="6" :lg="6">
                <el-form-item label="允许校区超额" prop="overPriceEnabled">
                  <el-switch v-model="dataForm.overPriceEnabled" :active-value="true" :inactive-value="false" :style="{ width: '100%' }"></el-switch>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="6" :lg="6">
                <el-form-item label="超额价格" prop="overPrice">
                  <el-input v-model="dataForm.overPrice" placeholder="请输入" clearable></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="16">
              <el-col :xs="24" :sm="12" :md="12" :lg="12" v-if="custom.hasFormP('registerDate')">
                <el-form-item label="报名日期" prop="registerDate">
                  <el-date-picker v-model="dataForm.registerDate" placeholder="请选择" clearable required :style="{ width: '100%' }" type="daterange" range-separator="至" format="yyyy-MM-dd" start-placeholder="开始日期" end-placeholder="结束日期" value-format="timestamp"></el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="12" v-if="custom.hasFormP('trainDate')">
                <el-form-item label="师训日期" prop="trainDate">
                  <el-date-picker v-model="dataForm.trainDate" placeholder="请选择" clearable required :style="{ width: '100%' }" type="datetimerange" range-separator="至" format="yyyy-MM-dd HH:mm" value-format="timestamp" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>
          <!-- 人数与排序区：设置总人数、校区名额、期数与发布排序等容量与展示参数 -->
          <el-card class="cu-section-card" shadow="never">
            <div slot="header">
              <groupTitle content-identity="left" content="人数与排序" icon="el-icon-user"></groupTitle>
            </div>
            <el-row :gutter="16">
              <el-col :xs="24" :sm="12" :md="6" :lg="6" v-if="custom.hasFormP('maxPerson')">
                <el-form-item label="师训总人数" prop="maxPerson">
                  <el-input-number v-model="dataForm.maxPerson" placeholder="数字文本" required :step="1" controls-position="right" :style="{ width: '100%' }"></el-input-number>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="6" :lg="6" v-if="custom.hasFormP('campsMaxPerson')">
                <el-form-item label="校区参训名额" prop="campsMaxPerson">
                  <el-input-number v-model="dataForm.campsMaxPerson" placeholder="数字文本" required :step="1" controls-position="right" :style="{ width: '100%' }"></el-input-number>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="6" :lg="6" v-if="custom.hasFormP('nper')">
                <el-form-item label="师训期数" prop="nper">
                  <el-input-number v-model="dataForm.nper" placeholder="数字文本" required :step="1" controls-position="right" :style="{ width: '100%' }"></el-input-number>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="6" :lg="6" v-if="custom.hasFormP('sortCode')">
                <el-form-item label="发布排序" prop="sortCode">
                  <el-input-number v-model="dataForm.sortCode" placeholder="数字文本" required :step="1" controls-position="right" :style="{ width: '100%' }"></el-input-number>
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>
          <!-- 地点与围栏区：设置详细地址并解析经纬度，同时配置电子围栏半径与测试功能 -->
          <el-card class="cu-section-card" shadow="never">
            <div slot="header">
              <groupTitle content-identity="left" content="地点与围栏" icon="el-icon-location"></groupTitle>
            </div>
            <el-row :gutter="16">
              <el-col :xs="24" :sm="24" :md="18" :lg="18" v-if="custom.hasFormP('address')">
                <el-form-item label="师训地址" prop="address">
                  <el-input 
                    v-model="dataForm.address" 
                    placeholder="请输入详细地址，例如：北京市朝阳区建国路88号" 
                    clearable 
                    required 
                    :style="{ width: '100%' }"
                    @blur="handleAddressChange"
                  >
                    <el-button 
                      slot="append" 
                      @click="parseAddress" 
                      :loading="addressParsing"
                      type="primary"
                      icon="el-icon-location"
                    >
                      {{ addressParsing ? '解析中...' : '获取坐标' }}
                    </el-button>
                    <el-button 
                      slot="append" 
                      @click="doReverseGeocode" 
                      type="default"
                      icon="el-icon-map-location"
                    >
                      逆解析
                    </el-button>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="6" :lg="6">
                <el-form-item label="围栏距离(米)" prop="radius">
                  <el-input 
                    v-model="dataForm.radius" 
                    placeholder="电子围栏距离" 
                    clearable
                    type="number"
                    @input="handleRadiusInput"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="16">
              <el-col :xs="24" :sm="12" :md="8" :lg="6">
                <el-form-item label="经度" prop="longitude">
                  <el-input 
                    v-model="dataForm.longitude" 
                    placeholder="经度" 
                    disabled
                    @blur="handleCoordinateChange"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="8" :lg="6">
                <el-form-item label="纬度" prop="latitude">
                  <el-input 
                    v-model="dataForm.latitude" 
                    placeholder="纬度" 
                    disabled
                    @blur="handleCoordinateChange"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="8" :lg="6">
                <el-form-item> 
                  <el-button 
                    @click="openMobileTest" 
                    :disabled="!canTestDistance"
                    type="primary"
                    size="small"
                    style="margin-left:8px"
                  >
                    手机扫码测试
                  </el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>

          <!-- 内容与承诺区：编辑培训内容、启用承诺书及其文本，用于报名端展示与确认 -->
          <el-card class="cu-section-card" shadow="never">
            <div slot="header">
              <groupTitle content-identity="left" content="内容与承诺" icon="el-icon-edit"></groupTitle>
            </div>
            <el-row :gutter="16">
              <el-col :xs="24" :sm="24" :md="24" :lg="24" v-if="custom.hasFormP('content')">
                <el-form-item label="师训内容" prop="content">
                  <custom-quill v-model="dataForm.content" placeholder="请输入内容..." imgType="train" required fileSize="10"></custom-quill>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="16">
              <el-col :xs="24" :sm="12" :md="6" :lg="6" >
                <el-form-item label="开启承诺书" prop="isAttach">
                  <el-switch v-model="dataForm.isAttach" :active-value="true" :inactive-value="false" :style="{ width: '100%' }"></el-switch>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="24" :md="18" :lg="24">
                <el-form-item label="承诺书内容" prop="additionalText">
                  <custom-quill v-model="dataForm.additionalText" placeholder="请输入内容..." required fileSize="10"></custom-quill>
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>
          <el-col :span="24" v-if="false">
            <el-form-item label="师训编号" prop="enCode">
              <el-input v-model="dataForm.enCode" placeholder="请输入" clearable :style="{ width: '100%' }"></el-input>
            </el-form-item>
          </el-col>
          

          
          <!-- 高级选项区：配置报名表单项，用于扩展收集报名信息的字段 -->
          <el-card class="cu-section-card" shadow="never">
            <div slot="header">
              <groupTitle content-identity="left" content="报名表单设置" icon="el-icon-setting"></groupTitle>
            </div>
            <el-row>
              <el-col :xs="24" :sm="24" :md="24" :lg="24">
                <el-form-item label-width="0">
                  <el-table :data="dataForm.formJson" size="mini" empty-text="点击下方“添加”按钮">
                    <el-table-column type="index" width="50" label="序号" align="center" />
                    <el-table-column prop="label" label="标题">
                      <template slot-scope="scope">
                        <el-input v-model="scope.row.label" placeholder="请输入标题" clearable></el-input>
                      </template>
                    </el-table-column>
                    <el-table-column prop="type" label="类型">
                      <template slot-scope="scope">
                        <el-select v-model="scope.row.type" placeholder="请选择类型" clearable>
                          <el-option v-for="(item, index) in typeOptions" :key="index" :label="item.fullName" :value="item.enCode"></el-option>
                        </el-select>
                      </template>
                    </el-table-column>
                    <el-table-column prop="required" label="是否必填">
                      <template slot-scope="scope">
                        <el-switch v-model="scope.row.required" active-text="是" inactive-text="否"></el-switch>
                      </template>
                    </el-table-column>
                    <el-table-column prop="defaultValue" label="默认值">
                      <template slot-scope="scope">
                        <el-input v-model="scope.row.defaultValue" placeholder="请输入默认值" clearable></el-input>
                      </template>
                    </el-table-column>
                    <el-table-column prop="options" label="选项">
                      <template slot-scope="scope">
                        <el-input v-model="scope.row.options" placeholder="请输入选项" clearable></el-input>
                      </template>
                    </el-table-column>
                    <el-table-column prop="placeholder" label="提示消息">
                      <template slot-scope="scope">
                        <el-input v-model="scope.row.placeholder" placeholder="请输入提示消息" clearable></el-input>
                      </template>
                    </el-table-column>
                    <el-table-column label="操作" width="50">
                      <template slot-scope="scope">
                        <el-button size="mini" type="text" class="cu-table-delBtn" @click="handleDelExtForm(scope.$index)">删除</el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                  <div class="table-actions" @click="addHandleExtForm()">
                    <el-button type="text" icon="el-icon-plus">添加</el-button>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>
        </el-form>
      </div>
      <el-dialog title="手机扫码定位测试" :visible.sync="mobileDialogVisible" width="360px" append-to-body>
        <div style="display:flex;flex-direction:column;align-items:center;gap:8px">
          <img :src="mobileQrDataUrl" alt="QR" class="qr-img" />
          <div style="color:#606266;font-size:12px">请使用手机扫码打开测试页面，允许定位后查看距离与围栏判定结果</div>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="mobileDialogVisible = false">关 闭</el-button>
        </span>
      </el-dialog>
      <campus-relation-list v-if="campusRelationListVisible" ref="CampusRelationList" @refreshDataList="initData" />
    </div>
  </transition>
</template>

<script>
import { getTrainInfo, createTrain, updateTrain } from '@/api/campus/train'
import { geocodeAddress, reverseGeocodePoint, calculateDistance, waitForBMap, validateCoordinates, validateRadius } from '@/utils/mapUtils'
import QRCode from 'qrcode'

export default {
  props: [],
  data() {
    return {


      loading: false,
      visible: false,
      campusRelationListVisible: false,
      isDetail: false,
      dataForm: {
        id: '',
        title: undefined,
        typeId: undefined,
        picture: [],
        pushCampus: undefined,
        model: undefined,
        free: 0,
        price: 0.0,
        overPriceEnabled: false,
        overPrice: 0.0,
        maxPerson: 0,
        campsMaxPerson: 0,
        registerDate: undefined,
        trainDate: undefined,
        nper: 0,
        sortCode: 0,
        address: undefined,
        content: undefined,
        enCode: undefined,
        enabledMark: 0,
        certificateTemplate: undefined,
        formJson: undefined,
        isAttach: false,
        additionalText: undefined,
        longitude: undefined, // 新增经度字段
        latitude: undefined, // 新增纬度字段
        radius: undefined,

      },
      rules: {
          longitude: [
          {
            required: true,
            message: '请输入师训详细地址，并点击获取坐标按钮',
            trigger: 'change'
          }
        ],
         latitude: [
          {
            required: true,
            message: '请输入师训详细地址，并点击获取坐标按钮',
            trigger: 'change'
          }
        ], 
        brand: [
          {
            required: true,
            message: '请选择要推送的品牌',
            trigger: 'change'
          }
        ],
        picture: [
          {
            required: true,
            message: '请上传宣传图片',
            trigger: 'blur'
          }
        ],
        title: [
          {
            required: true,
            message: '请输入师训标题',
            trigger: 'blur'
          }
        ],
        certificateTemplate: [
          {
            required: true,
            message: '请选择师训类型',
            trigger: 'change'
          }
        ],
        typeId: [
          {
            required: true,
            message: '请选择证书模版',
            trigger: 'change'
          }
        ],
        price: [
          {
            required: true,
            message: '请输入收费价格',
            trigger: 'blur'
          },
          {
            pattern: /^\d+(\.\d{1,2})?$/,
            message: '请输入正确的金额',
            trigger: 'blur'
          }
        ],
        overPriceEnabled: [
          {
            required: false,
            trigger: 'change'
          }
        ],
        overPrice: [
          {
            required: false,
            trigger: 'blur'
          },
          {
            pattern: /^\d+(\.\d{1,2})?$/,
            message: '请输入正确的金额',
            trigger: 'blur'
          }
        ],
        maxPerson: [
          {
            required: true,
            message: '请输入师训总人数',
            trigger: ['blur', 'change']
          }
        ],
        campsMaxPerson: [
          {
            required: true,
            message: '请输入校区参训名额',
            trigger: ['blur', 'change']
          }
        ],
        trainDate: [
          {
            required: true,
            message: '请输入师训日期',
            trigger: 'change'
          }
        ],
        registerDate: [
          {
            required: true,
            message: '请输入报名日期',
            trigger: 'change'
          }
        ],
        nper: [
          {
            required: true,
            message: '请输入师训期数',
            trigger: ['blur', 'change']
          }
        ],
        sortCode: [
          {
            required: true,
            message: '请输入发布排序',
            trigger: ['blur', 'change']
          }
        ],
        address: [
          {
            required: true,
            message: '请输入师训地址',
            trigger: 'blur'
          }
        ],
        content: [
          {
            required: true,
            message: '请输入师训内容',
            trigger: 'blur'
          }
        ],
        radius: [
          {
            required: true,
            message: '请输入电子围栏距离',
            trigger: 'blur'
          }
        ]
      },
      brandOptions: [],
      typeIdOptions: [],
      modelOptions: [{ enCode: true, fullName: '线上' }, { enCode: false, fullName: '线下' }],
      certificateTemplateOptions: [],
      typeOptions: [{ enCode: 'text', fullName: '单行文本' }, { enCode: 'textarea', fullName: '多行文本' }, { enCode: 'radio', fullName: '单选' }, { enCode: 'checkbox', fullName: '多选' }],
      
      // 地址解析状态
      addressParsing: false,
      addressResolving: false,
      coordinateResolving: false
      , mobileDialogVisible: false
      , mobileQrDataUrl: ''
    }
  },
  computed: {
    canTestDistance() {
      return this.dataForm.longitude && this.dataForm.latitude && this.dataForm.radius
    }
  },
  watch: {},
  created() {
    this.$store.dispatch('base/getDictionaryData', { sort: 'Brand' }).then(res => {
      this.brandOptions = res
    })
    this.$store.dispatch('base/getDictionaryData', { sort: 'TrainType' }).then(res => {
      this.typeIdOptions = res.filter(t => t.enabledMark == 1)
    })
    this.$store.dispatch('base/getDictionaryData', { sort: 'TrainCertificateType' }).then(res => {
      this.certificateTemplateOptions = res.filter(t => t.enabledMark == 1)
    })
  },
  mounted() {
    this.$nextTick(() => this.initMapPreview())
  },
  watch: {
    'dataForm.longitude'(v) {
      this.updateFenceCircle()
    },
    'dataForm.latitude'(v) {
      this.updateFenceCircle()
    }
  },
  methods: {
    async initMapPreview() {
      try {
        await waitForBMap()
        const root = this.$refs.mapPreview
        if (!root) return
        if (!this._map) {
          this._map = new BMap.Map(root)
        }
        const lng = Number(this.dataForm.longitude) || 116.404
        const lat = Number(this.dataForm.latitude) || 39.915
        const center = new BMap.Point(lng, lat)
        this._map.enableScrollWheelZoom(true)
        this._map.centerAndZoom(center, 15)
        if (this._marker) {
          this._map.removeOverlay(this._marker)
        }
        this._marker = new BMap.Marker(center)
        this._marker.enableDragging()
        this._marker.addEventListener('dragend', (e) => {
          const p = e.point
          this.dataForm.longitude = p.lng
          this.dataForm.latitude = p.lat
          this.updateFenceCircle()
        })
        this._map.addOverlay(this._marker)
        this.updateFenceCircle()
      } catch (e) {
        this.$message.error(e.message || '地图预览初始化失败')
      }
    },
    updateFenceCircle() {
      if (!this._map) return
      const lng = Number(this.dataForm.longitude)
      const lat = Number(this.dataForm.latitude)
      if (!validateCoordinates(lng, lat)) return
      const center = new BMap.Point(lng, lat)
      if (this._circle) {
        this._map.removeOverlay(this._circle)
      }
      const radius = Number(this.dataForm.radius) || 0
      this._circle = new BMap.Circle(center, radius, { strokeColor: '#409EFF', fillColor: '#409EFF', fillOpacity: 0.2, strokeWeight: 2 })
      this._map.addOverlay(this._circle)
      this._map.panTo(center)
    },
    async doReverseGeocode() {
      const lng = Number(this.dataForm.longitude)
      const lat = Number(this.dataForm.latitude)
      if (!validateCoordinates(lng, lat)) {
        this.$message.warning('请先设置有效的经纬度坐标')
        return
      }
      try {
        const addr = await reverseGeocodePoint(lng, lat)
        this.dataForm.address = addr
        this.$message.success('逆解析成功')
      } catch (e) {
        this.$message.error(e.message || '逆解析失败')
      }
    },
    handleRadiusInput(val) {
      const num = Number(val)
      if (!validateRadius(num)) {
        this.$message.warning('围栏半径建议设置在 1~3000 米范围内')
      }
      this.$nextTick(() => this.updateFenceCircle())
    },

    /**
     * 将文本生成二维码DataURL（北京时间：2025-11-13）
     */
    async qrToDataUrl(text) {
      return await QRCode.toDataURL(text, { width: 240, margin: 1 })
    },

    goBack() {
      this.$emit('refresh')
    },
    init(id, isDetail) {
      this.dataForm.id = id || 0
      this.visible = true
      this.isDetail = isDetail || false
      this.$nextTick(() => {
        this.$refs['elForm'].resetFields()
        if (this.dataForm.id) {
          getTrainInfo(this.dataForm.id).then(res => {
            let data = Object.assign({ isAttach: false, additionalText: undefined }, res.data)
            this.dataForm = data
            if (!this.dataForm.picture) this.dataForm.picture = []
          })
        }
      })
    },
    dataFormSubmit() {
      this.$refs['elForm'].validate(valid => {
        if (valid) {

          this.loading = true
          const formMethod = this.dataForm.id ? updateTrain : createTrain
          formMethod(this.dataForm)
            .then(res => {
              this.loading = false
              this.$message({
                message: res.msg,
                type: 'success',
                duration: 1000,
                onClose: () => {
                  this.visible = false
                  this.$emit('refresh', true)
                }
              })
            })
            .catch(error => {
              this.loading = false
              this.$message.error(error.message || '保存失败，请重试')
            })
        }
      })
    },
    closeDialog() {
      this.$refs['elForm'].resetFields()
    },

    handleDelExtForm(index) {
      this.dataForm.formJson.splice(index, 1)
    },
    addHandleExtForm() {
      let item = {
        label: undefined,
        type: undefined,
        required: undefined,
        defaultValue: undefined,
        options: undefined,
        placeholder: undefined
      }
      if (this.dataForm.formJson == null) {
        this.dataForm.formJson = []
      }
      this.dataForm.formJson.push(item)
    },
    

    
    // 解析地址获取坐标
    async parseAddress() {
      if (!this.dataForm.address || !this.dataForm.address.trim()) {
        this.$message.warning('请先输入师训地址')
        return
      }
      
      try {
        this.addressParsing = true
        const result = await geocodeAddress(this.dataForm.address)
        this.dataForm.longitude = result.longitude
        this.dataForm.latitude = result.latitude
        this.$message.success('地址解析成功，已自动填入经纬度')
      } catch (error) {
        this.$message.error(error.message || '地址解析失败，请检查地址是否正确')
      } finally {
        this.addressParsing = false
      }
    },
    
    // 地址变更处理
    async handleAddressChange() {
      // 地址变更时可以选择自动解析坐标
    },
    
    // 坐标变更处理
    async handleCoordinateChange() {
      this.updateFenceCircle()
    },
    
    // 测试距离计算
     testDistance() {
       if (!this.dataForm.longitude || !this.dataForm.latitude) {
         this.$message.warning('请先设置师训地点的经纬度坐标')
         return
       }
       
       // 获取用户当前位置进行距离测试
       if (navigator.geolocation) {
         navigator.geolocation.getCurrentPosition(
           async (position) => {
             try {
               const userLat = position.coords.latitude
               const userLng = position.coords.longitude
               const distance = await calculateDistance(
                 userLat, userLng,
                 this.dataForm.latitude, this.dataForm.longitude
               )
               
               const radius = this.dataForm.radius || 0
               const isInRange = distance <= radius
               
               this.$alert(
                 `当前位置距离师训地点：${distance}米\n` +
                 `电子围栏半径：${radius}米\n` +
                 `签到状态：${isInRange ? '可以签到' : '超出范围'}`,
                 '距离测试结果',
                 {
                   confirmButtonText: '确定',
                   type: isInRange ? 'success' : 'warning'
                 }
               )
             } catch (error) {
               this.$message.error(error.message || '距离计算失败')
             }
           },
          (error) => {
            let errorMsg = '获取位置失败'
            switch (error.code) {
              case error.PERMISSION_DENIED:
                errorMsg = '用户拒绝了定位请求'
                break
              case error.POSITION_UNAVAILABLE:
                errorMsg = '位置信息不可用'
                break
              case error.TIMEOUT:
                errorMsg = '定位请求超时'
                break
            }
            this.$message.error(errorMsg)
          },
          {
            enableHighAccuracy: true,
            timeout: 10000,
            maximumAge: 60000
          }
        )
      } else {
        this.$message.error('浏览器不支持地理定位功能')
      }
    },
    /**
     * 生成手机扫码定位测试的二维码并弹窗展示（北京时间：2025-11-13）
     */
    async openMobileTest() {
      try {
        const origin = "https://trainsign.anqinyun.com"
        const lng = this.dataForm.longitude
        const lat = this.dataForm.latitude
        const radius = this.dataForm.radius || 0
        const title = encodeURIComponent(this.dataForm.title || '师训地点')
        const url = `${origin}/location-test?id=${this.dataForm.id}&lng=${lng}&lat=${lat}&radius=${radius}&title=${title}`
        const dataUrl = await this.qrToDataUrl(url)
        this.mobileQrDataUrl = dataUrl
        this.mobileDialogVisible = true
      } catch (e) {
        this.$message.error(e.message || '二维码生成失败')
      }
    }
  }
}
</script>
<style scoped>
.cu-section-card {
  margin-bottom: 16px;
}
.cu-section-card :deep(.el-card__header) {
  padding: 8px 16px;
}
.table-actions {
  margin-top: 8px;
}
.map-preview {
  width: 100%;
  height: 240px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  margin-top: 8px;
}
.qr-img { width: 240px; height: 240px; object-fit: contain; border: 1px solid #ebeef5; border-radius: 4px; }
